# -*- coding: utf-8 -*-
from natsort import natsorted
import sys, os
from PySide6.QtCore import Qt, QTimer, QSize, QRect
from PySide6.QtGui import QPainter
from PySide6.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
from PySide6.QtSvg import QSvgRenderer  # 正确的导入方式


def get_svg_files(path):

    svg_files = []
    if os.path.isdir(path):
        for root, dirs, files in os.walk(path):
            for file in files:
                if file.lower().endswith(".svg"):
                    file_path = os.path.join(root, file)
                    svg_files.append(file_path)
    # 按文件修改时间排序
    svg_files = natsorted(
        svg_files, key=lambda x: os.path.basename(x).lower()
    )  # 按文件名排序
    return svg_files


blick_eye = get_svg_files("res/emoji/blick_eye")
# smile = get_svg_files("res/emoji/smile")


class AnimatedSvgWidget(QWidget):
    EXPRESSIONS = {
        "default": {
            "frames": blick_eye,
            "interval": 8,
        },
        # "smile": {
        #     "frames": smile,
        #     "interval": 8,
        # },
    }

    def __init__(self, parent=None):
        super().__init__(parent)
        self.renderer = QSvgRenderer()
        self.current_frame = 0
        self.frames = []
        self.setFixedSize(200, 200)
        self.animation_timer = QTimer(self)
        self.animation_timer.timeout.connect(self.update_frame)
        self.set_expression("default")

    def set_expression(self, expression_name):
        expression = self.EXPRESSIONS.get(expression_name)
        if not expression:
            return

        self.frames = expression["frames"]
        self.animation_timer.setInterval(expression["interval"])

        if len(self.frames) > 1:
            self.animation_timer.start()
        else:
            self.animation_timer.stop()

        self.current_frame = 0
        self.load_frame(self.frames[self.current_frame])

    def load_frame(self, path):
        if self.renderer.load(path):
            self.update()  # 触发重绘
            # print(f"Loaded SVG: {path} ({self.renderer.defaultSize()})")
        else:
            print(f"Failed to load: {path}")

    def paintEvent(self, event):
        """自定义绘制方法"""
        painter = QPainter(self)
        self.renderer.render(painter, QRect(0, 0, self.width(), self.height()))

    def update_frame(self):
        self.current_frame = self.current_frame + 1
        if self.current_frame >= len(self.frames):
            self.animation_timer.stop()
            return
        self.load_frame(self.frames[self.current_frame])

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.set_expression("default")
        elif event.button() == Qt.RightButton:
            self.set_expression("smile")
